<template>
  <div class="user-info-container">
    <el-card class="user-info-card">
      <template #header>
        <div class="card-header">
          <span>用户基本信息</span>
        </div>
      </template>
      
      <el-form ref="userInfoForm" :model="userInfo" label-width="100px" class="user-info-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname" :rules="[
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称不能包含空白字符，长度1-10个字符', trigger: 'blur' }
        ]">
          <el-input v-model="userInfo.nickname" placeholder="请输入昵称（1-10个非空白字符）" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email" :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]">
          <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="用户头像" prop="userPic">
          <div class="avatar-container">
            <el-image :src="userInfo.userPic" alt="用户头像" class="user-avatar" />
          </div>
        </el-form-item>
        
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="formattedCreateTime" disabled />
        </el-form-item>
        
        <el-form-item label="更新时间" prop="updateTime">
          <el-input v-model="formattedUpdateTime" disabled />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交修改</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElImage, ElMessage } from 'element-plus'
import request from '../utils/request.js'
import useUserStore from '../store/user.js'

// 获取用户 store
const userStore = useUserStore()

// 表单引用
const userInfoForm = ref(null)

// 用户信息数据
const userInfo = ref({
  id: '',
  username: '',
  nickname: '',
  email: '',
  userPic: '',
  createTime: '',
  updateTime: ''
})

// 格式化时间
const formattedCreateTime = computed(() => {
  if (userInfo.value.createTime) {
    return new Date(userInfo.value.createTime).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  return ''
})

const formattedUpdateTime = computed(() => {
  if (userInfo.value.updateTime) {
    return new Date(userInfo.value.updateTime).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  return ''
})

// 备份原始用户信息，用于取消操作
let originalUserInfo = {}

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await request.get('/user/userInfo')
    if (response.code === 0) {
      userInfo.value = response.data
      // 备份原始信息
      originalUserInfo = { ...response.data }
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息错误:', error)
    ElMessage.error('获取用户信息失败，请重试')
  }
}

// 提交修改
const handleSubmit = async () => {
  try {
    // 验证表单
    await userInfoForm.value.validate()
    
    // 准备提交的数据
    const submitData = {
      id: userInfo.value.id,
      nickname: userInfo.value.nickname,
      email: userInfo.value.email
    }
    
    // 调用更新接口
    const response = await request.put('/user/update', submitData)
    
    if (response.code === 0) {
      ElMessage.success('修改成功')
      // 重新获取用户信息，确保全局状态同步
      await getUserInfo()
    } else {
      ElMessage.error(response.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改用户信息错误:', error)
    // 如果是表单验证错误，不显示额外提示
    if (!error.message || !error.message.includes('Validation failed')) {
      ElMessage.error('修改失败，请重试')
    }
  }
}

// 取消修改
const handleCancel = () => {
  // 恢复原始信息
  userInfo.value = { ...originalUserInfo }
  // 重置表单验证状态
  userInfoForm.value.resetFields()
}

// 组件挂载时获取用户信息
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.user-info-container {
  padding: 20px;
  height: 100%;
}

.user-info-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.user-info-form {
  margin-top: 20px;
}

.avatar-container {
  display: inline-block;
}

.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>